package top.hepingan.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.User;
import top.hepingan.java.mapper.UserMapper;
import top.hepingan.java.utils.AliUploadUtils;
import top.hepingan.java.utils.UserUtils;

import java.util.Random;
import java.util.UUID;

@RequestMapping("/system")
@RestController
@Slf4j
@RequiredArgsConstructor
public class SystemController {

    private final AliUploadUtils aliUploadUtils;

    @Value("${ali-oss.domain}")
    private String domain;

    /**
     * 纯上传图片
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadImg")
    public Result uploadImg2(@RequestBody MultipartFile file){
        String newFileName = generateRandomString();
        String url = aliUploadUtils.uploadFile(file, "hykj", newFileName+".jpg", true);
        return Result.data(domain + url);
    }

    @PostMapping("/deleteImg")
    public Result deleteImg(@RequestBody String url){
        aliUploadUtils.deleteFileByUrl(url);
        return Result.ok();
    }

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestBody MultipartFile file){
        String newFileName = generateRandomString();
        String url = aliUploadUtils.uploadFile(file, "hykj", newFileName, false);
        return Result.data(domain + url);
    }

    private String generateRandomString() {
        String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        int STRING_LENGTH = 12;
        Random random = new Random();
        StringBuilder sb = new StringBuilder(STRING_LENGTH);
        for (int i = 0; i < STRING_LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }


}
